﻿package com.mirror.llk.util;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;

import com.mirror.frame.log4j.ILog;
import com.mirror.frame.log4j.Logger;
import com.mirror.frame.utils.BaseUtils;

/**
 * @Title: 处理客户端HTTP调用方法
 * @Description:
 * @Copyright: Copyright (c) 2012-7-30
 * @Company: 幻方朗睿
 * @Author: Andy.D
 * @Version: 1.0
 */
public class ClientHttpConUtil {

    @Logger
    private static ILog log;

    public static String clientHttpConnection(String req, String url) {
        log.info("发送请求地址：" + url);
        HttpClient httpclient = new HttpClient();
        httpclient.getParams().setBooleanParameter("http.protocol.expect-continue", false);

        HttpConnectionManagerParams params = httpclient.getHttpConnectionManager().getParams();
        params.setConnectionTimeout(ConfigCache.getHttpClientConnectTimeout());
        params.setSoTimeout(ConfigCache.getHttpClientSoTimeout());

        PostMethod meth = null;

        String backXml = null;
        try {
            meth = new PostMethod(url);
            meth.setRequestHeader("Connection", "close");

            meth.setRequestEntity(new StringRequestEntity(req, Constant.HTTP_XML.CONTENT_TYPE, null));
            httpclient.executeMethod(meth);
            backXml = meth.getResponseBodyAsString();
            log.info("接收请求地址：" + url + BaseUtils.getLineSeparator() + "输出参数：" + backXml);
        }
        catch (Exception e) {
            log.error("调用接口失败:" + url, e);
        }
        finally {
            if (meth != null) {
                meth.releaseConnection();
            }

            ((SimpleHttpConnectionManager) httpclient.getHttpConnectionManager()).shutdown();
        }
        return backXml;
    }
}